package com.homework.dao;

import com.homework.config.ResourceConfig;
import com.homework.model.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/17 23:35
 */

@Repository
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDao {
    @Autowired
    private Connection conn ;

    public int insert(User user) {
        /**
         * todo: 写出对应的sql
         */
        String sql = "INSERT INTO tb_user(name, password) VALUES (?, ?)";
        try (
                PreparedStatement ps =  conn.prepareStatement(sql) ;
                ){
            ps.setString(1, user.getName());
            ps.setString(2, user.getPassword());
            return ps.executeUpdate(); // 返回受影响的行数
        } catch (Exception e) {
            /**
             * todo: 异常输出
             */
            e.printStackTrace(); // 输出异常信息
        }
        return 0 ;
    }

    /**
     * todo: 实现登录
     * @param name
     * @param password
     * @return
     */
    public User login(String name, String password) {
        String sql = "SELECT * FROM tb_user WHERE name = ? AND password = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id")); // 假设 User 类有 id 字段
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
                return user; // 返回找到的用户
            }
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常信息
        }
        return null; // 登录失败
    }

    /**
     * todo: 统计所有的用户数
     * @return
     */
    public int countAllUsers() {
        String sql = "SELECT COUNT(*) FROM tb_user";
        try (PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()
        ) {
            if (rs.next()) {
                return rs.getInt(1); // 返回用户总数
            }
        } catch (SQLException e) {
            e.printStackTrace(); // 输出异常信息
        }
        return 0; // 返回 0 表示统计失败
    }

}
